package com.le.tester.book.effectivejava3rdchinese.articlefortyfive;

import java.io.File;
import java.io.FileNotFoundException;
import java.lang.reflect.Array;
import java.util.*;

/**
 * createTime：2022/8/25 9:30
 * description：读取颠倒的字母
 */
public class Anagrams {
    public static void main(String[] args) throws FileNotFoundException {
        File dictionary = new File(args[0]);

        int minGroupSize = Integer.parseInt(args[1]);

        Map<String, Set<String>> groups = new HashMap<>();

        //scanner 在读取文件的时候会无声的吞噬掉异常
        try (Scanner s = new Scanner(dictionary)) {

            while (s.hasNext()) {
                String word = s.nextLine();

                //可以返回被关联的值，key存在的话，就会直接返回，
                groups.computeIfAbsent(alphabetize(word), (unused) -> new TreeSet<>()).add(word);
            }
        }

        for (Set<String> group : groups.values()) {
            if (group.size() >= minGroupSize) {
                System.out.println(group.size() + ": " + group);
            }
        }
    }

    private static String alphabetize(String s) {
        char[] a = s.toCharArray();
        Arrays.sort(a);
        return new String(a);
    }
}
